package models;

import java.util.ArrayList;
import java.util.List;

import javax.cache.Cache;

import com.google.gson.Gson;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;


import entities.ApiConfig;
import helpers.GeneralHelper;
import helpers.GoogleStorageHelper;
import helpers.StringHelper;


public class ApiConfigModel  {
	
	private Cache cache = null;
	
	private String cachePrefix = "api_config_";
	
	private static ApiConfigModel instance = null;
	
	public static ApiConfigModel getInstance() {
		if (instance == null) {
			instance = new ApiConfigModel();
		}
		
		return instance;
	}
	
	private ApiConfigModel() {
		try {
			ObjectifyService.register(ApiConfig.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
	}
	
	public ApiConfig get(String id) {
		String cacheName = cachePrefix  + id;
		boolean isCached = false;
		
		ApiConfig apiConfig = null;
		if (cache != null) {
			try {
				apiConfig = (ApiConfig) cache.get(cacheName);
				if (apiConfig != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			String filename = "/gs/static.hatforrent.com/api/" + id + ".txt";
			String jsonObject = GoogleStorageHelper.readFileGoogleStorage(filename);
			
			//String jsonObject = StringHelper.getContentFromUrl("http://static.hatforrent.com/api/" + id + ".txt");
			
			if (jsonObject != null) {
				apiConfig = new Gson().fromJson(jsonObject, ApiConfig.class);
				if (cache != null && apiConfig != null) {
					try {
						cache.put(cacheName, apiConfig);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		}
		return apiConfig;
	}
	
	public void cleanCache(String id) {
		String cacheName = cachePrefix  + id;
		
		if (cache != null) {
			try {
				cache.remove(cacheName);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
}
